package com.ms.oschina.fragment;

import java.io.IOException;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;

import com.ms.oschina.adapter.FriendsAdapter;
import com.ms.oschina.adapter.PageIndexListAdapter;
import com.ms.oschina.api.remote.OsChinaApi;
import com.ms.oschina.base.BaseListFragment;
import com.ms.oschina.bean.Active;
import com.ms.oschina.bean.Constants;
import com.ms.oschina.util.LocalBroadcastUtils;
import com.ms.oschina.util.LogUtils;
import com.ms.oschina.util.UiUtils;

public class FriendsFragment extends BaseListFragment<Active> {

	private UserUpdateReceiver mReceiver;

	@Override
	public PageIndexListAdapter<Active> getAdapter() {
		FriendsAdapter synthesizeAdapter = new FriendsAdapter(getListView(),
				getNetData(), true);
		return synthesizeAdapter;
	}

	@Override
	public List<Active> getNetData(int pageIndex) throws IOException {
		List<Active> friendsInfo = OsChinaApi.getFriendsInfo(pageIndex);
		if (friendsInfo == null) {// 用户未登陆
			setErrorPager("请登陆后操作", new OnClickListener() {
				@Override
				public void onClick(View v) {
					UiUtils.login();
				}
			});
		}
		return friendsInfo;
	}

	@Override
	public void initEvent() {
		mReceiver = new UserUpdateReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.ACTION_EXTERNAL_USERCHANGE);
		LocalBroadcastUtils.registerReceiver(intentFilter, mReceiver);
	}

	@Override
	public void onDestroy() {
		LocalBroadcastUtils.unRegisterReceiver(mReceiver);
		mReceiver = null;
		super.onDestroy();
	}

	private class UserUpdateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			refreshData();
		}
	}
}
